package review;

import java.util.Arrays;

public class 归并排序 {

    private static void chaifen(int[] array, int low, int high) {
        if (low >= high) {
            return;
        }
        int mid = (low + high) / 2;
        chaifen(array, low, mid);
        chaifen(array, mid + 1, high);
        merger(array, low, mid, high);
    }

    /**
     * 将片段进行合并
     */
    private static void merger(int[] array, int low, int mid, int high) {
        int i = low;
        int j = mid + 1;
        int[] temp = new int[high - low + 1];
        int index = 0;
        while (i <= mid && j <= high) {
            if (array[i] < array[j]) {
                temp[index] = array[i];
                i++;
            } else {
                // 存在有序对，
                temp[index] = array[j];
                j++;
            }
            index++;
        }
        while (i <= mid) {
            temp[index] = array[i];
            i++;
            index++;
        }
        while (j <= high) {
            temp[index] = array[j];
            j++;
            index++;
        }
        for (int h = 0; h < temp.length; h++) {
            array[low + h] = temp[h];
        }
    }


    public static void chai(int[] array,int low,int high) {
        if(low >= high) {
            return;
        }
        int mid = (low + high)/2;
        chai(array,low,mid);
        chai(array,low + 1,high);
        mer(array,low,mid,high);

    }

    public static void mer(int[] array,int low,int mid,int high) {
        int i = low;
        int j = mid;
        int[] temp = new int[high - low + 1];
        int index = 0;
        while (i <= mid && j <= high) {
            if(array[i] < array[j]) {
                temp[index] = array[i];
                i++;
            } else {
                temp[index] = array[j];
                j++;
            }
            index++;
        }
        while (i <= mid) {
            temp[index] = array[i];
            i++;
            index++;
        }
        while (j <= high) {
            temp[index] = array[j];
            j++;
            index++;
        }
        for (int k = 0; k < temp.length; k++) {
            array[low + k] = temp[k];
        }
    }

    public static void main(String[] args) {
        int[] a = {10, 8, 5, 60, 9, 2, 6, 3};
        chaifen(a, 0, a.length - 1);
        System.out.println(Arrays.toString(a));
    }
}
